package com.eco.fanliapp.controller.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eco.fanliapp.common.constant.ApiEnum;
import com.eco.fanliapp.common.constant.WechatConfig;
import com.eco.fanliapp.entity.*;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.utils.ExceptionUtil;
import com.eco.fanliapp.utils.SHA1Utils;
import com.eco.fanliapp.utils.UUIDUtils;
import com.eco.fanliapp.vo.WxCodeDto;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @ProjectName: fanliapp
 * @Package: com.eco.fanliapp.controller.app
 * @ClassName: WxController
 * @Author: xiaoxx
 * @Description: 版本号
 * @Date: 2019/11/28 15:13
 * @Version: 4.2.2
 */
@Controller
@RequestMapping("/wx")
public class WxController {

    private static final Logger log = LoggerFactory.getLogger(WxController.class);

    @SuppressWarnings("rawtypes")
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    private IAppUserService appUserService;
    @Autowired
    private IAppNewsLogService appNewsLogService;
    @Autowired
    private IAppCompanyService appCompanyService;
    @Autowired
    private ISyUserWxContrastService syUserWxContrastService;
    @Autowired
    private IAppWxWithdrawalService appWxWithdrawalService;
    @Autowired
    private ISyChannelUserService syChannelUserService;
    @Autowired
    private ISyChannelService syChannelService;

    @Autowired
    private RedisTemplateService redisTemplateService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping(produces = "text/plain;charset=utf-8")
    @ResponseBody
    public String token(String signature, String timestamp, String nonce, String echostr) {
        log.info("进入服务器配置================");
        String token = WechatConfig.TOKEN;
        if (!(StringUtils.isEmpty(signature) && StringUtils.isEmpty(timestamp) && StringUtils.isEmpty(nonce))) {
            List<String> list = new ArrayList<>();
            list.add(timestamp);
            list.add(token);
            list.add(nonce);
            Collections.sort(list);
            String s = list.get(0) + list.get(1) + list.get(2);
            if (SHA1Utils.encode(s).equals(signature)) {
                log.info("返回给微信：" + echostr);
                return echostr;
            }
        }
        log.info("服务异常提示");
        return "error";
    }

    @PostMapping(produces = "text/xml;charset=utf-8")
    @ResponseBody
    public void weixinPost(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        log.info("进入post回调");
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter out = resp.getWriter();
        try {
            //接收微信请求参数
            Map<String, String> map = WeixinUtil.xmlToMap(req);
            String toUserName = map.get("ToUserName");
            String fromUserName = map.get("FromUserName");
            String msgType = map.get("MsgType");
            String content = map.get("Content");
            String msgId = map.get("MsgId");
            log.info("ToUserName:{},FromUserName:{},MsgType:{},Content:{},MsgId:{}", toUserName, fromUserName, msgType, content, msgId);

            //判断请求是否事件类型 event
            String message = null;
            if (WechatConfig.MESSAGE_EVENT.equals(msgType)) {
                String eventType = map.get("Event");
                log.info("输出消息类型:" + eventType);
                //关注公众号事件  subscribe
                String mycontent = null;
                if (WechatConfig.EVENT_SUB.equals(eventType)) {
                    mycontent = "欢迎关注~\n首次提现需点击下方菜单栏“提现”按钮，即可到账呦！";
                    message = WeixinUtil.initText(toUserName, fromUserName, mycontent, msgId); //(工具類已做處理)set属性值的时候，注意：ToUserName 和 FromUserName的值要反过来！是坑!是坑!是坑!
                    //处理用户openId
                    log.info("=============开始处理openId:{}相关业务", fromUserName);
                    handlerOpenId(fromUserName);
                    log.info("=============结束处理openId:{}相关业务", fromUserName);
                }
                //点击按钮，触发提现接口
                if (WechatConfig.EVENT_CLICK.equals(eventType)) {
                    log.info("点击提现：开始进入提现服务");
                    message = appWxWithdrawalService.getResponseMessage(toUserName, fromUserName, msgId);
                }
            }
            //回复提现二字，触发提现接口
            if (WechatConfig.MESSAGE_TEXT.equals(msgType)) {
                if ("提现".equals(content)) {
                    log.info("回复提现：开始进入提现服务");
                    message = appWxWithdrawalService.getResponseMessage(toUserName, fromUserName, msgId);
                }
            }
            log.info("响应给微信的{}", message);
            if (message == null || "".equals(message)) {
                String mycontent2 = "对话功能暂不支持！";
                message = WeixinUtil.initText(toUserName, fromUserName, mycontent2, msgId);
            }
            out.print(message);
        } catch (Exception e) {
            e.printStackTrace();
            out.close();
        }
    }

    private void handlerOpenId(String wxOpendId) {
        log.info("=========关注公众号，开始处理openId:{}", wxOpendId);
        //查询这个用户openId是否存在
        QueryWrapper<SyUserWxContrast> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("wx_opend_id", wxOpendId);
        queryWrapper.eq("enable", true);
        queryWrapper.eq("deleted", false);
        List<SyUserWxContrast> listWxContrast = syUserWxContrastService.list(queryWrapper);
        if (CollectionUtils.isEmpty(listWxContrast)) {
            try {
                //获取access_token
                String accessToken = appWxWithdrawalService.getAccessToken();
                //根据用户openId,获取用户信息
                net.sf.json.JSONObject userInfo = WeixinUtil.getUserInfo(accessToken, wxOpendId);
                if (userInfo != null) {
                    //保存用户信息
                    log.info("关注公众号，用户unionid:{}", userInfo.getString("unionid"));
                    SyUserWxContrast contrast = new SyUserWxContrast();
                    contrast.setUnionId(userInfo.getString("unionid"));
                    contrast.setWxOpendId(wxOpendId);
                    syUserWxContrastService.save(contrast);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        log.info("==========关注公众号，结束处理openId:{}", wxOpendId);
    }

    /**
     * 微信授权回调
     *
     * @param session
     * @param state
     * @param code
     * @param appid
     * @param modelMap
     * @param response
     * @return
     * @throws UnsupportedEncodingException
     */
    @GetMapping("/wxOpenAuth")
    public String wxOpenAuth(HttpSession session, String state, String code, String appid,
                             ModelMap modelMap, HttpServletResponse response) throws UnsupportedEncodingException {
        log.info("微信回调请求参数，state:{}, code:{},appid:{},modelMap:{}", state, code, appid, modelMap);
        if (StringUtils.isNotEmpty(code)) {
            WxCodeDto wxCodeDto = getWxCode(code);
            if (wxCodeDto == null) {
                wxCodeDto = new WxCodeDto();
                String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + WechatConfig.APPID + "&secret=" + WechatConfig.APPSECRET + "&code=" + code + "&grant_type=authorization_code";
                RestTemplate restTemplate = new RestTemplate();
                String res = restTemplate.getForObject(url, String.class);
                JSONObject jsonObject = JSONObject.parseObject(res);
                if (StringUtils.isEmpty(jsonObject.getString("errcode"))) {
                    wxCodeDto.setAccess_token(jsonObject.getString("access_token"));
                    wxCodeDto.setOpenid(jsonObject.getString("openid"));
                    wxCodeDto.setRefresh_token(jsonObject.getString("refresh_token"));
                    saveWxCode(code, wxCodeDto);
                } else {
                    String redirectUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + WechatConfig.APPID + "&redirect_uri=" + WechatConfig.RETURNURL + "&response_type=code&scope=snsapi_userinfo&state=share:" + state + "#wechat_redirect";
                    return "redirect:" + redirectUrl;
                }
            }

            //判断access_token是否有效
            log.info("判断access_token是否有效:{}", wxCodeDto.getAccess_token());
            String checkAccessToken = "https://api.weixin.qq.com/sns/auth?access_token=" + wxCodeDto.getAccess_token() + "&openid=" + wxCodeDto.getOpenid();
            RestTemplate restTemplate = new RestTemplate();
            String cheRes = restTemplate.getForObject(checkAccessToken, String.class);
            @SuppressWarnings("rawtypes")
            Map chemap = JSON.parseObject(cheRes);
            if (StringUtils.isNotEmpty((String) chemap.get("errmsg")) && chemap.get("errmsg").equals("ok")) {
            } else {
                //重新刷新access_token
                String accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + appid + "&grant_type=refresh_token&refresh_token=" + wxCodeDto.getRefresh_token();
                String accRes = restTemplate.getForObject(accessTokenUrl, String.class);
                @SuppressWarnings("rawtypes")
                Map accmap = JSON.parseObject(accRes);
                if (StringUtils.isNotEmpty((String) accmap.get("access_token"))) {
                    wxCodeDto.setAccess_token((String) accmap.get("access_token"));
                }
            }
            if (StringUtils.isNotEmpty(wxCodeDto.getAccess_token()) &&
                    StringUtils.isNotEmpty(wxCodeDto.getOpenid())) {
                //获取用户信息
                String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + wxCodeDto.getAccess_token() + "&openid=" + wxCodeDto.getOpenid() + "&lang=zh_CN";
                String userRes = restTemplate.getForObject(userInfoUrl, String.class);
                try {
                    userRes = new String(userRes.getBytes("ISO-8859-1"), "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    ExceptionUtil.errorMsg(WxController.class, e);
                }
                JSONObject userJsonObject = JSONObject.parseObject(userRes);
                if (StringUtils.isEmpty(userJsonObject.getString("errcode"))) {
                    String nickName = userJsonObject.getString("nickname");
                    String headimgurl = userJsonObject.getString("headimgurl");
                    String unionid = userJsonObject.getString("unionid");
                    String appOpenid = userJsonObject.getString("openid");
                    log.info("用户信息参数：nickName:{}，headimgurl{},unionid:{},appOpenid:{}", nickName, headimgurl, unionid, appOpenid);
                    AppUser superUser = null;

                    //新增用户
                    AppUser appUser2 = new AppUser();

                    AppUser user = appUserService.selectAppUserByWechatUnionid(unionid);
                    String shareStr = "share:";
                    String goodsStr = "goods:";
                    String invitecodeStr = "invitecode:";
                    String channelCodeStr = "channelCode:";

                    if (user == null || StringUtils.isBlank(user.getWechatUnionid())) {
                        appUser2.setWechatUnionid(unionid);
                        appUser2.setWechatNickname(nickName);
                        appUser2.setUserName(nickName);
                        appUser2.setUserImgUrl(headimgurl);
//                        appUser2.setInviteCode(state.split(":")[1]);//联盟邀请码
                        appUser2.setMeInviteCode(UUIDUtils.generateShortUuid());
//                      appUser2.setSuperInviteCode(state.split(":")[1]);//上级邀请码
                        //微信已授权
                        appUser2.setUserWechatAuthorization(2);
                        //淘宝未授权
                        appUser2.setUserTaobaoAuthorization(1);
                        appUser2.setAppLogin(1);
                    }
                    //邀请海报
                    if (state.contains(shareStr)) {
                        superUser = appUserService.selectAppUserByUserId(NumberUtils.toLong(state.split(":")[1]), 1);
                        if (user == null || StringUtils.isBlank(user.getWechatUnionid())) {
                            log.info("邀请赚钱进入邀请新用户{}", unionid);
                            if (superUser != null && superUser.getUserId() != null) {
                                //上级邀请码
                                appUser2.setSuperInviteCode(superUser.getMeInviteCode());
                                appUser2.setCompanyId(superUser.getCompanyId());
                            }
                        }
                        //商品详情分享
                    } else if (state.contains(goodsStr)) {
                        superUser = appUserService.selectAppUserByUserId(NumberUtils.toLong(state.split(":")[1]), 1);
                        if (user == null || StringUtils.isBlank(user.getWechatUnionid())) {
                            log.info("商品详情进入邀请新用户{}", unionid);
                            if (superUser != null && superUser.getUserId() != null) {
                                //上级邀请码
                                appUser2.setSuperInviteCode(superUser.getMeInviteCode());
                                appUser2.setCompanyId(superUser.getCompanyId());
                            }
                        }
                        //invitecode:公司分享链接;
                    } else if (state.contains(invitecodeStr)) {
                        if (user == null || StringUtils.isBlank(user.getWechatUnionid())) {
                            log.info("公司分享进入邀请新用户{}", user.getWechatUnionid());
                            appUser2.setCompanyId(NumberUtils.toInt(state.split(":")[2]));
                            String company_id = state.split(":")[2];
                            String inviteCode = state.split(":")[1];

                            if (company_id != null) {
                                AppCompany appCompany = appCompanyService.selectAppCompanyById(Integer.parseInt(company_id));
                                appUser2.setCompanyId(appCompany.getCompanyId());

                            } else if (inviteCode != null) {
                                AppCompany appCompany = appCompanyService.findtAppCompanyInviteCode(inviteCode);
                                appUser2.setCompanyId(appCompany.getCompanyId());
                            }
                        }
                        //channelCode:渠道邀请码
                    } else if (state.contains(channelCodeStr)) {
                        if (user == null || StringUtils.isBlank(user.getWechatUnionid())) {
                            log.info("公司分享进入邀请新用户{}", user == null ? null : user.getWechatUnionid());
                            //构建用户信息
                            appUser2 = addAppUser(appUser2, unionid, nickName, headimgurl, state);
                        }
                    }
                    //用户不存在
                    if (user == null || StringUtils.isBlank(user.getWechatUnionid())) {

                        if (appUser2.getCompanyId() == null) {
                            //总公司
                            AppCompany companyAll = appCompanyService.findtAppCompany(null, 1);
                            appUser2.setCompanyId(companyAll.getCompanyId());
                        }

                        //保存用户基本信息
                        int i = appUserService.insertAppUser(appUser2);
                        //保存用户openId
                        saveUserOpenId(unionid, appOpenid);
                        if (state.contains(channelCodeStr)) {
                            //保存用户渠道信息
                            saveSyChannelUer(unionid, state.split(":")[1]);
                        }
                        if (i > 0) {
                            if (state.contains(invitecodeStr)) {
                                log.info("message公司邀请新增成功{}用户unionid{}微信名称{}公司邀请码{}公司id{}", i, unionid, nickName, appUser2.getInviteCode(), appUser2.getCompanyId());
                            } else if (state.contains(channelCodeStr)) {
                                log.info("收集渠道用户信息结束");
                            } else {
                                log.info("message邀请新增成功{}用户unionid{}微信名称{}邀请码{}", i, unionid, nickName, appUser2.getSuperInviteCode());
                            }
                        } else {
                            if (state.contains(invitecodeStr)) {
                                log.error("message公司邀请新增失败{}用户unionid{}微信名称{}公司邀请码{}公司id{}", i, unionid, nickName, appUser2.getInviteCode(), appUser2.getCompanyId());
                            } else if (state.contains(channelCodeStr)) {
                                log.info("收集渠道用户信息结束===失败");
                            } else {
                                log.error("message邀请新增失败{}用户unionid{}微信名称{}邀请码{}", i, unionid, nickName, appUser2.getSuperInviteCode());
                            }
                        }
                        //用户已存在
                    } else {
                        log.info("message邀请用户已存在{}", user.getWechatUnionid());
                        if (superUser != null && superUser.getUserId() != null
                                && user.getUserId() != null && user.getAppLogin() != null && user.getAppLogin() == 1
                                && (user.getSuperInviteCode() == null || "".equals(user.getSuperInviteCode()))
                                && superUser.getUserId().intValue() != user.getUserId().intValue() && !superUser.getMeInviteCode().equals(user.getMeInviteCode())) {

                            AppUser appUser3 = new AppUser();
                            appUser3.setTableId(user.getTableId());
                            //上级邀请码
                            appUser3.setSuperInviteCode(superUser.getMeInviteCode());
                            appUserService.updateById(appUser3);
                            log.info("如果用户没有上级，且没有授权登陆，被要求时，将上级邀请码更新进来被执行{}上级邀请码{}", user.getWechatUnionid(), appUser3.getSuperInviteCode());
                        }
                    }
                    String redisKeyStr = "app_wechatConfigSnsShareUrl_url";
                    String wechatConfigSnsShareUrl = WechatConfig.SNS_SHARE_URL;
                    if (redisTemplate.hasKey(redisKeyStr)) {
                        try {
                            wechatConfigSnsShareUrl = stringRedisTemplate.opsForValue().get(redisKeyStr);
                        } catch (Exception e) {
                            log.info("微信进行转发url{}newUrl{}", WechatConfig.SNS_SHARE_URL, wechatConfigSnsShareUrl);
                        }
                    }
                    String redirectUrl = null;
                    String redirectYuming1 = WechatConfig.RED_MONEY_URL;
                    String redirectYuming2 = WechatConfig.RED_MONEY_COMMUNITY_URL;
                    String redirectYuming3 = WechatConfig.NYZH_RED_MONEY_URL;

                    String redisKeyStr1 = "app_wechatConfigRED_MONEY_URL_url";
                    String redisKeyStr2 = "app_wechatConfigRED_MONEYCommunity_URL_url";
                    if (redisTemplateService.hasKey(redisKeyStr1)) {
                        try {
                            redirectYuming1 = redisTemplateService.getTByKey(redisKeyStr1, String.class);
                        } catch (Exception e) {
                            log.info("微信进行转发url{}newUrl{}", WechatConfig.RED_MONEY_URL, redirectYuming1);
                        }
                    }
                    if (redisTemplateService.hasKey(redisKeyStr2)) {
                        try {
                            redirectYuming2 = redisTemplateService.getTByKey(redisKeyStr2, String.class);
                        } catch (Exception e) {
                            log.info("微信进行转发url{}newUrl{}", WechatConfig.RED_MONEY_COMMUNITY_URL, redirectYuming2);
                        }
                    }

                    if (state.contains(shareStr)) {
                        Long userId = null;
                        String invitedCode = null;
                        if (state.split(":").length >= 2) {
                            userId = NumberUtils.toLong(state.split(":")[1]);
                        }
                        if (state.split(":").length >= 3) {
                            invitedCode = state.split(":")[2];
                        }
                        AppUser user2 = appUserService.selectAppUserByUserId(userId, 1);
                        String str = "type=0&jumpType=1&linkType=0" + "&invitedCode=" + invitedCode;
                        String data = "shengya!!!" + str + "shengya!!!";
                        return "redirect:" + wechatConfigSnsShareUrl + "/flashSale?type=0&jumpType=1&linkType=0" + "&invitedCode=" + invitedCode
                                + "&str=" + URLEncoder.encode(data, "UTF-8")
                                + "&link_name=" + URLEncoder.encode(user2 == null ? "" : user2.getUserName(), "UTF-8")
                                + "&link_icon=" + URLEncoder.encode(user2 == null ? "" : user2.getUserImgUrl(), "UTF-8")
                                + "&connect_redirect=1#wechat_redirect";
//                        return "redirect:" + WechatConfig.SNS_SHARE_URL + "/flashSale?"
//                                + "link_name=" + URLEncoder.encode(user2 == null ? "" : user2.getUserName(), "UTF-8")
//                                + "&link_icon=" + URLEncoder.encode(user2 == null ? "" : user2.getUserImgUrl(), "UTF-8")
//                                + "#/flashSale";
//                        }
                    } else if (state.contains(goodsStr)) {
                        String str = "itemId=" + state.split(":")[2] + "&type=1&jumpType=1&linkType=0" + "&invitedCode=" + state.split(":")[3];
                        String data = "shengya!!!" + str + "shengya!!!";
                        return "redirect:" + wechatConfigSnsShareUrl + "/share?id=" + state.split(":")[2] + "&type=1&jumpType=1&linkType=0" + "&invitedCode=" + state.split(":")[4]
                                + "&str=" + URLEncoder.encode(data, "UTF-8")
                                + "&connect_redirect=1#wechat_redirect";
                    } else if (state.contains(channelCodeStr)) {
                        //WechatConfig.RED_MONEY_URL;
                        Integer companyId = Integer.parseInt(state.split(":")[2]);
                        String channelCode = state.split(":")[1];
                        String str = "type=0&jumpType=1&linkType=0" + "&channelCode=" + channelCode;
                        String data = "shengya!!!" + str + "shengya!!!";
//                        log.info("公司==========================={}",companyId);
                        if (companyId != null) {
                            if (companyId == 42 || companyId == 43) {
                                redirectUrl = redirectYuming2 + "?type=0&jumpType=1&linkType=0" + "&channelCode=" + channelCode + "&str=" + URLEncoder.encode(data, "UTF-8");

                            } else if(companyId == 46){
                                redirectUrl = redirectYuming3 + "?type=0&jumpType=1&linkType=0" + "&channelCode=" + channelCode + "&str=" + URLEncoder.encode(data, "UTF-8");
                            }else {
                                redirectUrl = redirectYuming1 + "?type=0&jumpType=1&linkType=0" + "&channelCode=" + channelCode + "&str=" + URLEncoder.encode(data, "UTF-8");
                            }
                        } else {
                            redirectUrl = redirectYuming1 + "?type=0&jumpType=1&linkType=0" + "&channelCode=" + channelCode + "&str=" + URLEncoder.encode(data, "UTF-8");
                        }
                        return "redirect:" + redirectUrl;
                        //                        return "redirect:" + wechatConfigSnsShareUrl + "/app/pages/redMoney/";
                    } else if (state.contains(invitecodeStr)) {
                        if (user == null) {
                            return "wxApp";
                        } else {
                            return "redirect:" + wechatConfigSnsShareUrl + "/flashSale?"
                                    + "link_name=" + URLEncoder.encode(user == null ? "" : user.getUserName(), "UTF-8")
                                    + "&link_icon=" + URLEncoder.encode(user == null ? "" : user.getUserImgUrl(), "UTF-8")
                                    + "#/flashSale";
                        }
                    }
                    return "wxApp";
                }
            }
        }
        return "wxApp";
    }

    /**
     * 构建appUser信息
     *
     * @param appUser2
     */
    private AppUser addAppUser(AppUser appUser2, String unionid, String nickName, String headimgurl, String state) {
        //渠道邀请码
        String inviteCode = state.split(":")[1];
        log.info("开始构建appUser信息，渠道邀请码为inviteCode:{}", inviteCode);
        appUser2.setAppLogin(1);
        SyChannel syChannel = syChannelService.findSyChannelUserById(inviteCode, 1);
        if (syChannel != null) {
            //获取公司id
            Integer companyId = syChannel.getCompanyId();
            log.info("获取的公司companyId:{}", companyId);
            if (companyId != null) {
//					AppCompany appCompany = appCompanyService.findtAppCompany(companyId, 1);
                appUser2.setCompanyId(companyId);
                //获取公司邀请码
//                appUser2.setInviteCode(appCompany.getInviteCode());
            }
        }
        log.info("返回用户信息");
        return appUser2;
    }

    /**
     * 保存渠道用户信息
     *
     * @param unionid
     * @param inviteCode
     */
    private void saveSyChannelUer(String unionid, String inviteCode) {
        log.info("保存渠道用户信息");
        //根据unionid获取用户基本信息
        QueryWrapper<AppUser> query1 = new QueryWrapper<>();
        query1.eq("wechat_unionid", unionid);
        query1.eq("enable", true);
        List<AppUser> list1 = appUserService.list(query1);
        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(list1)) {
            //校验用户渠道信息是否已经存在
            AppUser appUser = list1.get(0);
            QueryWrapper<SyChannelUser> query2 = new QueryWrapper<>();
            query2.eq("user_id", appUser.getUserId());
            query2.eq("enable", true);
            query2.eq("deleted", false);
            List<SyChannelUser> list2 = syChannelUserService.list(query2);
            if (org.apache.commons.collections.CollectionUtils.isNotEmpty(list2)) {
                log.info("渠道用户信息已经存在，不允许重复创建");
                return;
            }
            //根据渠道邀请码获取渠道信息
            SyChannel syChannel = syChannelService.findSyChannelUserById(inviteCode, 1);
            if (syChannel != null) {
                SyChannelUser channelUser = new SyChannelUser();
                channelUser.setUserId(appUser.getUserId());
                channelUser.setChannelId(syChannel.getTableId());
                channelUser.setChannelName(syChannel.getChannelName());
                channelUser.setChannelInviteCode(syChannel.getChannelInviteCode());
                syChannelUserService.save(channelUser);
                log.info("保存用户渠道信息成功");
                return;

            }
            log.info("根据渠道邀请码未获取到该渠道");
            return;
        }
        log.info("根据用户unionid未获取到该用户信息");

    }

    /**
     * 保存用户openId
     *
     * @param unionid
     * @param appOpenid
     */
    private void saveUserOpenId(String unionid, String appOpenid) {
        log.info("执行新增用户，记录该用户的openId::执行保存用户unionId方法");
        //判断unionId是否保存过
        QueryWrapper<SyUserWxContrast> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("union_id", unionid);
        queryWrapper.eq("enable", true);
        queryWrapper.eq("deleted", false);
        List<SyUserWxContrast> wxContrastList = syUserWxContrastService.list(queryWrapper);
        if (CollectionUtils.isEmpty(wxContrastList)) {
            //保存用户信息（unionId，appOpenId)
            SyUserWxContrast contrast = new SyUserWxContrast();
            contrast.setUnionId(unionid);
            contrast.setWxOpendId(appOpenid);
            boolean b = syUserWxContrastService.save(contrast);
            log.info("用户unionid:" + unionid + "保存用户app登陆授权信息结果：" + b);
        }
        log.info("该用户的openId已经存在");
    }

    WxCodeDto getWxCode(String code) {
        return (WxCodeDto) redisTemplate.opsForValue().get("wxcode:" + code);
    }

    @SuppressWarnings("unchecked")
    void saveWxCode(String code, WxCodeDto wxCodeDto) {
        redisTemplate.opsForValue().set("WxCode:" + code, wxCodeDto, 7100, TimeUnit.SECONDS);
    }

    //判断当前时间是不是在30天以内
    public static Boolean is30Time(Long a) {
        //获取注册时间第N天后的时间
        if (System.currentTimeMillis() < getDateTime(a, ApiEnum.FENS_EXPIRE_TIME)) {
            return true;
        } else {
            return false;
        }
    }

    // 获取指定时间的时间戳
    private static long getDateTime(Long a, Integer start) {

        return DateUtils.addDays(new Date(a), start).getTime();
    }

    //查询用户邀请次数
    private Boolean isCount(Long userId) {
        Integer count = appNewsLogService.findFenSiCount(userId);
        count = count == null ? 0 : count;
        if (count <= ApiEnum.FENS_COUNT) {
            return true;
        } else {
            return false;
        }
    }


}
